/**
 * 可视化变量插入器组件
 */
import React, { useState, useEffect } from 'react';
import {
  Modal,
  Tree,
  Input,
  Button,
  Space,
  Tag,
  Tooltip,
  Tabs,
  Card,
  List,
  Typography,
  Alert,
} from 'antd';
import {
  DatabaseOutlined,
  FieldStringOutlined,
  FieldNumberOutlined,
  MailOutlined,
  CalendarOutlined,
  UserOutlined,
  TableOutlined,
  CodeOutlined,
  CopyOutlined,
} from '@ant-design/icons';
import type { DataNode } from 'antd/es/tree';
import {
  getDataSources,
  type DataSourceItem,
} from '@/services/dataSource';
import {
  getDataSourceFields,
  type DataSourceField,
  FieldType,
  getFieldTypeLabel,
} from '@/services/dataSourceField';

const { Search } = Input;
const { TabPane } = Tabs;
const { Text, Paragraph } = Typography;

interface VariableInserterProps {
  visible: boolean;
  onClose: () => void;
  onInsert: (variable: string) => void;
  currentDataSourceId?: number;
}

interface VariableTemplate {
  name: string;
  description: string;
  template: string;
  category: 'basic' | 'conditional' | 'loop' | 'table';
}

const VariableInserter: React.FC<VariableInserterProps> = ({
  visible,
  onClose,
  onInsert,
  currentDataSourceId,
}) => {
  const [loading, setLoading] = useState(false);
  const [dataSources, setDataSources] = useState<DataSourceItem[]>([]);
  const [selectedDataSource, setSelectedDataSource] = useState<number | undefined>(currentDataSourceId);
  const [fields, setFields] = useState<DataSourceField[]>([]);
  const [searchText, setSearchText] = useState('');
  const [activeTab, setActiveTab] = useState('fields');

  // 获取数据源列表
  const fetchDataSources = async () => {
    try {
      const response = await getDataSources({ page: 1, size: 100 });
      setDataSources(response.items);
      if (!selectedDataSource && response.items.length > 0) {
        setSelectedDataSource(response.items[0].id);
      }
    } catch (error) {
      console.error('获取数据源失败:', error);
    }
  };

  // 获取字段列表
  const fetchFields = async (dataSourceId: number) => {
    setLoading(true);
    try {
      const fieldList = await getDataSourceFields(dataSourceId);
      setFields(fieldList);
    } catch (error) {
      console.error('获取字段失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (visible) {
      fetchDataSources();
    }
  }, [visible]);

  useEffect(() => {
    if (selectedDataSource) {
      fetchFields(selectedDataSource);
    }
  }, [selectedDataSource]);

  // 获取字段图标
  const getFieldIcon = (fieldType: FieldType) => {
    const iconMap = {
      [FieldType.TEXT]: <FieldStringOutlined />,
      [FieldType.NUMBER]: <FieldNumberOutlined />,
      [FieldType.EMAIL]: <MailOutlined />,
      [FieldType.DATE]: <CalendarOutlined />,
      [FieldType.DATETIME]: <CalendarOutlined />,
      [FieldType.BOOLEAN]: <CodeOutlined />,
      [FieldType.JSON]: <CodeOutlined />,
      [FieldType.LONGTEXT]: <FieldStringOutlined />,
      [FieldType.URL]: <FieldStringOutlined />,
      [FieldType.PHONE]: <FieldStringOutlined />,
      [FieldType.CURRENCY]: <FieldNumberOutlined />,
    };
    return iconMap[fieldType] || <FieldStringOutlined />;
  };

  // 获取字段颜色
  const getFieldColor = (field: DataSourceField) => {
    if (field.is_email) return 'green';
    if (field.is_name) return 'blue';
    if (field.is_primary) return 'red';
    if (field.field_type === FieldType.NUMBER) return 'orange';
    return 'default';
  };

  // 构建数据源树结构
  const buildDataSourceTree = (): DataNode[] => {
    return dataSources.map(ds => ({
      title: ds.name,
      key: `ds-${ds.id}`,
      icon: <DatabaseOutlined />,
      children: fields
        .filter(field => 
          !searchText || 
          field.name.toLowerCase().includes(searchText.toLowerCase()) ||
          (field.display_name && field.display_name.toLowerCase().includes(searchText.toLowerCase()))
        )
        .map(field => ({
          title: (
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              {getFieldIcon(field.field_type)}
              <span>{field.display_name || field.name}</span>
              <Tag color={getFieldColor(field)} size="small">
                {getFieldTypeLabel(field.field_type)}
              </Tag>
              {field.is_email && <Tag color="green" size="small">邮箱</Tag>}
              {field.is_name && <Tag color="blue" size="small">姓名</Tag>}
            </div>
          ),
          key: `field-${field.id}`,
          isLeaf: true,
          field,
        })),
    }));
  };

  // 处理字段选择
  const handleFieldSelect = (field: DataSourceField) => {
    const variable = `{{${field.name}}}`;
    onInsert(variable);
  };

  // 变量模板
  const variableTemplates: VariableTemplate[] = [
    {
      name: '简单变量',
      description: '插入单个字段值',
      template: '{{field_name}}',
      category: 'basic',
    },
    {
      name: '条件显示',
      description: '根据条件显示不同内容',
      template: '{% if condition %}显示内容{% endif %}',
      category: 'conditional',
    },
    {
      name: '条件选择',
      description: '根据条件选择显示内容',
      template: '{% if condition %}内容1{% else %}内容2{% endif %}',
      category: 'conditional',
    },
    {
      name: '循环列表',
      description: '循环显示列表数据',
      template: '{% for item in items %}\n- {{item.name}}: {{item.value}}\n{% endfor %}',
      category: 'loop',
    },
    {
      name: '数据表格',
      description: '显示表格格式的数据',
      template: '<table>\n{% for row in data %}\n<tr>\n  <td>{{row.col1}}</td>\n  <td>{{row.col2}}</td>\n</tr>\n{% endfor %}\n</table>',
      category: 'table',
    },
    {
      name: '带序号列表',
      description: '带序号的循环列表',
      template: '{% for item in items %}\n{{loop.index}}. {{item.name}}\n{% endfor %}',
      category: 'loop',
    },
  ];

  // 过滤模板
  const getFilteredTemplates = (category?: string) => {
    return variableTemplates.filter(template => 
      !category || template.category === category
    ).filter(template =>
      !searchText || 
      template.name.toLowerCase().includes(searchText.toLowerCase()) ||
      template.description.toLowerCase().includes(searchText.toLowerCase())
    );
  };

  return (
    <Modal
      title="插入变量"
      open={visible}
      onCancel={onClose}
      footer={null}
      width={800}
      style={{ top: 20 }}
    >
      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane tab="数据字段" key="fields">
          <div style={{ marginBottom: 16 }}>
            <Space direction="vertical" style={{ width: '100%' }}>
              <Search
                placeholder="搜索字段名称"
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                allowClear
              />
              
              {dataSources.length > 1 && (
                <div>
                  <Text strong>选择数据源：</Text>
                  <div style={{ marginTop: 8 }}>
                    <Space wrap>
                      {dataSources.map(ds => (
                        <Button
                          key={ds.id}
                          type={selectedDataSource === ds.id ? 'primary' : 'default'}
                          size="small"
                          onClick={() => setSelectedDataSource(ds.id)}
                        >
                          {ds.name}
                        </Button>
                      ))}
                    </Space>
                  </div>
                </div>
              )}
            </Space>
          </div>

          <div style={{ maxHeight: 400, overflowY: 'auto' }}>
            <List
              loading={loading}
              dataSource={fields.filter(field => 
                !searchText || 
                field.name.toLowerCase().includes(searchText.toLowerCase()) ||
                (field.display_name && field.display_name.toLowerCase().includes(searchText.toLowerCase()))
              )}
              renderItem={(field) => (
                <List.Item
                  actions={[
                    <Tooltip title="插入变量">
                      <Button
                        type="text"
                        icon={<CopyOutlined />}
                        onClick={() => handleFieldSelect(field)}
                      />
                    </Tooltip>
                  ]}
                >
                  <List.Item.Meta
                    avatar={getFieldIcon(field.field_type)}
                    title={
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span>{field.display_name || field.name}</span>
                        <Tag color={getFieldColor(field)} size="small">
                          {getFieldTypeLabel(field.field_type)}
                        </Tag>
                        {field.is_email && <Tag color="green" size="small">邮箱</Tag>}
                        {field.is_name && <Tag color="blue" size="small">姓名</Tag>}
                      </div>
                    }
                    description={
                      <div>
                        <div>字段名：<Text code>{field.name}</Text></div>
                        {field.description && <div>描述：{field.description}</div>}
                        {field.sample_value && <div>样例：{field.sample_value}</div>}
                      </div>
                    }
                  />
                </List.Item>
              )}
              locale={{ emptyText: '暂无字段数据' }}
            />
          </div>
        </TabPane>

        <TabPane tab="模板语法" key="templates">
          <div style={{ marginBottom: 16 }}>
            <Search
              placeholder="搜索模板"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              allowClear
            />
          </div>

          <Tabs tabPosition="left" size="small">
            <TabPane tab="基础语法" key="basic">
              <List
                dataSource={getFilteredTemplates('basic')}
                renderItem={(template) => (
                  <List.Item
                    actions={[
                      <Button
                        type="text"
                        icon={<CopyOutlined />}
                        onClick={() => onInsert(template.template)}
                      >
                        插入
                      </Button>
                    ]}
                  >
                    <List.Item.Meta
                      title={template.name}
                      description={
                        <div>
                          <div>{template.description}</div>
                          <Paragraph code copyable={{ text: template.template }}>
                            {template.template}
                          </Paragraph>
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
            </TabPane>

            <TabPane tab="条件语法" key="conditional">
              <List
                dataSource={getFilteredTemplates('conditional')}
                renderItem={(template) => (
                  <List.Item
                    actions={[
                      <Button
                        type="text"
                        icon={<CopyOutlined />}
                        onClick={() => onInsert(template.template)}
                      >
                        插入
                      </Button>
                    ]}
                  >
                    <List.Item.Meta
                      title={template.name}
                      description={
                        <div>
                          <div>{template.description}</div>
                          <Paragraph code copyable={{ text: template.template }}>
                            {template.template}
                          </Paragraph>
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
            </TabPane>

            <TabPane tab="循环语法" key="loop">
              <List
                dataSource={getFilteredTemplates('loop')}
                renderItem={(template) => (
                  <List.Item
                    actions={[
                      <Button
                        type="text"
                        icon={<CopyOutlined />}
                        onClick={() => onInsert(template.template)}
                      >
                        插入
                      </Button>
                    ]}
                  >
                    <List.Item.Meta
                      title={template.name}
                      description={
                        <div>
                          <div>{template.description}</div>
                          <Paragraph code copyable={{ text: template.template }}>
                            {template.template}
                          </Paragraph>
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
            </TabPane>

            <TabPane tab="表格语法" key="table">
              <List
                dataSource={getFilteredTemplates('table')}
                renderItem={(template) => (
                  <List.Item
                    actions={[
                      <Button
                        type="text"
                        icon={<CopyOutlined />}
                        onClick={() => onInsert(template.template)}
                      >
                        插入
                      </Button>
                    ]}
                  >
                    <List.Item.Meta
                      title={template.name}
                      description={
                        <div>
                          <div>{template.description}</div>
                          <Paragraph code copyable={{ text: template.template }}>
                            {template.template}
                          </Paragraph>
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
            </TabPane>
          </Tabs>
        </TabPane>

        <TabPane tab="语法说明" key="help">
          <Alert
            message="模板语法说明"
            description={
              <div>
                <p><strong>基础变量：</strong>使用 <Text code>{`{{variable_name}}`}</Text> 插入字段值</p>
                <p><strong>条件语句：</strong>使用 <Text code>{`{% if condition %}...{% endif %}`}</Text></p>
                <p><strong>循环语句：</strong>使用 <Text code>{`{% for item in items %}...{% endfor %}`}</Text></p>
                <p><strong>HTML支持：</strong>可以在模板中使用HTML标签进行格式化</p>
              </div>
            }
            type="info"
            showIcon
          />
        </TabPane>
      </Tabs>
    </Modal>
  );
};

export default VariableInserter;
